// PointCloudProcessor.js

class PointCloudProcessor {
    constructor() {
        this.pointCloudObject = null;
        // 使用统一的单位系统

        // 点云显示配置
        this.config = {
            colors: {
                near: new THREE.Color(0x0000FF),   // 近距离点颜色（蓝色）
                mid: new THREE.Color(0x8000FF),    // 中距离点颜色（紫色）
                far: new THREE.Color(0xB000FF)     // 远距离点颜色（浅紫色）
            },
            sizes: {
                near: 2.0,
                mid: 1.8,
                far: 1.5
            },
            distances: {
                near: 1.0,  // 1米
                mid: 2.0    // 2米
            },
            opacity: 0.9
        };
    }

    // 初始化点云对象
    initPointCloud() {
        if (!worldScene) {
            console.error('WorldScene is required for point cloud initialization');
            return false;
        }

        try {
            const geometry = new THREE.BufferGeometry();
            const material = new THREE.PointsMaterial({
                vertexColors: true,
                size: this.config.sizes.near,
                sizeAttenuation: false,
                transparent: true,
                opacity: this.config.opacity,
                depthWrite: false,
                blending: THREE.NormalBlending
            });

            this.pointCloudObject = new THREE.Points(geometry, material);
            this.pointCloudObject.name = 'lidarPointCloud';

            // 使用统一单位设置雷达高度
            const lidarHeight = robotConfig.lidar.height || 0.05; // 使用配置中的雷达高度或默认值
            this.pointCloudObject.position.y = lidarHeight * worldUnitsManager.UNIT_SCALE;
            this.pointCloudObject.renderOrder = 999;

            const scene = worldScene.getScene();
            if (!scene) {
                console.error('Scene not initialized in WorldScene');
                return false;
            }
            scene.add(this.pointCloudObject);
            return true;
        } catch (error) {
            console.error('Error initializing point cloud:', error);
            return false;
        }
    }

    // 更新点云数据
    updatePointCloud(pointCloudData) {
        if (!this.pointCloudObject) {
            if (!this.initPointCloud(worldScene)) {
                return;
            }
        }

        try {
            const points = pointCloudData.points;
            const numPoints = points.length;

            const positions = new Float32Array(numPoints * 3);
            const colors = new Float32Array(numPoints * 3);
            const sizes = new Float32Array(numPoints);

            points.forEach((point, i) => {
                if (!point || typeof point.x !== 'number' || typeof point.y !== 'number') {
                    return;
                }

                // 计算角度 (0-360度平均分布)
                const angle = (i / numPoints) * Math.PI * 2;

                // 将毫米转换为米
                const x = point.x * 0.001;  // mm to m
                const y = point.y * 0.001;  // mm to m
                const distance = Math.sqrt(x * x + y * y);

                // 使用角度计算最终位置并应用单位转换
                positions[i * 3] = Math.cos(angle) * distance * worldUnitsManager.UNIT_SCALE;
                positions[i * 3 + 1] = 0;  // 保持在同一平面
                positions[i * 3 + 2] = Math.sin(angle) * distance * worldUnitsManager.UNIT_SCALE;

                // 根据距离设置颜色和大小
                let color, size;
                if (distance < this.config.distances.near) {
                    color = this.config.colors.near;
                    size = this.config.sizes.near;
                } else if (distance < this.config.distances.mid) {
                    color = this.config.colors.mid;
                    size = this.config.sizes.mid;
                } else {
                    color = this.config.colors.far;
                    size = this.config.sizes.far;
                }

                colors[i * 3] = color.r;
                colors[i * 3 + 1] = color.g;
                colors[i * 3 + 2] = color.b;
                sizes[i] = size;
            });

            // 更新几何体
            if (this.pointCloudObject.geometry) {
                this.pointCloudObject.geometry.dispose();
            }

            const geometry = new THREE.BufferGeometry();
            geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
            geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
            geometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1));

            this.pointCloudObject.geometry = geometry;

        } catch (error) {
            console.error('Error updating point cloud:', error);
        }
    }

    // 清理资源
    dispose() {
        if (this.pointCloudObject) {
            if (this.pointCloudObject.geometry) {
                this.pointCloudObject.geometry.dispose();
            }
            if (this.pointCloudObject.material) {
                this.pointCloudObject.material.dispose();
            }
            if (this.pointCloudObject.parent) {
                this.pointCloudObject.parent.remove(this.pointCloudObject);
            }
            this.pointCloudObject = null;
        }
    }
}

// 点云初始化函数
function initPointCloudProcessor() {
    // 检查依赖
    if (typeof THREE === 'undefined') {
        console.error('THREE.js not loaded');
        return null;
    }

    if (typeof worldUnitsManager === 'undefined') {
        console.error('worldUnitsManager not defined');
        return null;
    }

    if (typeof robotConfig === 'undefined') {
        console.error('robotConfig not loaded');
        return null;
    }

    try {
        // 创建实例
        const pcp = new PointCloudProcessor();

        console.log('Point cloud processor initialized successfully');
        return pcp;
    } catch (error) {
        console.error('Failed to initialize point cloud processor:', error);
        return null;
    }
}

// 导出到全局作用域
if (typeof window !== 'undefined') {
    window.PointCloudProcessor = PointCloudProcessor;
    window.initPointCloudProcessor = initPointCloudProcessor;
}

// CommonJS 模块导出
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        PointCloudProcessor,
        initPointCloudProcessor
    };
}